import { HttpClient } from '../utils/HttpClient';
import { 
  LoginCredentials, 
  RegisterInfo, 
  LoginResult, 
  RegisterResult, 
  User, 
  AuthToken 
} from '../types';

export class AuthService {
  private httpClient: HttpClient;
  private currentUser: User | null = null;

  constructor() {
    this.httpClient = new HttpClient();
  }

  /**
   * 初始化认证服务
   */
  public async initializeAuth(): Promise<void> {
    try {
      const token = await this.getStoredToken();
      if (token && !this.isTokenExpired(token)) {
        await this.loadCurrentUser();
      } else {
        await this.clearAuthData();
      }
    } catch (error) {
      console.error('Failed to initialize auth:', error);
      await this.clearAuthData();
    }
  }

  /**
   * 用户登录
   */
  public async login(credentials: LoginCredentials): Promise<LoginResult> {
    try {
      const response = await this.httpClient.post('/auth/login', credentials);
      
      if (response.success && response.data) {
        const { user, token, refreshToken } = response.data;
        
        // 保存认证信息
        await this.saveAuthData({ 
          token, 
          refreshToken, 
          expiresAt: Date.now() + (7 * 24 * 60 * 60 * 1000) // 7天
        });
        
        // 保存用户信息
        await this.saveUserInfo(user);
        this.currentUser = user;
        
        return { 
          success: true, 
          user, 
          message: '登录成功' 
        };
      } else {
        return { 
          success: false, 
          message: response.message || '登录失败' 
        };
      }
    } catch (error) {
      console.error('Login failed:', error);
      return { 
        success: false, 
        message: '网络错误，请重试' 
      };
    }
  }

  /**
   * 用户注册
   */
  public async register(userInfo: RegisterInfo): Promise<RegisterResult> {
    try {
      // 前端验证
      const validation = this.validateRegisterInfo(userInfo);
      if (!validation.isValid) {
        return {
          success: false,
          message: validation.message
        };
      }

      const response = await this.httpClient.post('/auth/register', {
        username: userInfo.username,
        phone: userInfo.phone,
        password: userInfo.password
      });
      
      if (response.success && response.data) {
        return { 
          success: true, 
          user: response.data.user,
          message: '注册成功，请登录' 
        };
      } else {
        return { 
          success: false, 
          message: response.message || '注册失败' 
        };
      }
    } catch (error) {
      console.error('Registration failed:', error);
      return { 
        success: false, 
        message: '网络错误，请重试' 
      };
    }
  }

  /**
   * 用户登出
   */
  public async logout(): Promise<void> {
    try {
      await this.httpClient.post('/auth/logout');
    } catch (error) {
      console.error('Logout request failed:', error);
    } finally {
      await this.clearAuthData();
      this.currentUser = null;
    }
  }

  /**
   * 检查是否已认证
   */
  public async isAuthenticated(): Promise<boolean> {
    try {
      const token = await this.getStoredToken();
      if (!token || this.isTokenExpired(token)) {
        return false;
      }
      
      // 如果没有用户信息，尝试加载
      if (!this.currentUser) {
        await this.loadCurrentUser();
      }
      
      return this.currentUser !== null;
    } catch (error) {
      console.error('Failed to check authentication:', error);
      return false;
    }
  }

  /**
   * 获取当前用户
   */
  public getCurrentUser(): User | null {
    return this.currentUser;
  }

  /**
   * 刷新令牌
   */
  public async refreshToken(): Promise<boolean> {
    try {
      const refreshToken = await this.getStoredRefreshToken();
      if (!refreshToken) {
        return false;
      }

      const response = await this.httpClient.post('/auth/refresh', {
        refreshToken
      });

      if (response.success && response.data) {
        const { token, refreshToken: newRefreshToken } = response.data;
        
        await this.saveAuthData({
          token,
          refreshToken: newRefreshToken,
          expiresAt: Date.now() + (7 * 24 * 60 * 60 * 1000)
        });
        
        return true;
      }
      
      return false;
    } catch (error) {
      console.error('Token refresh failed:', error);
      return false;
    }
  }

  /**
   * 验证注册信息
   */
  private validateRegisterInfo(userInfo: RegisterInfo): { isValid: boolean; message?: string } {
    if (!userInfo.username || userInfo.username.trim().length < 3) {
      return { isValid: false, message: '用户名至少需要3个字符' };
    }

    if (!userInfo.phone || !/^1[3-9]\d{9}$/.test(userInfo.phone)) {
      return { isValid: false, message: '请输入有效的手机号' };
    }

    if (!userInfo.password || userInfo.password.length < 6) {
      return { isValid: false, message: '密码至少需要6个字符' };
    }

    if (userInfo.password !== userInfo.confirmPassword) {
      return { isValid: false, message: '两次输入的密码不一致' };
    }

    if (!userInfo.agreementAccepted) {
      return { isValid: false, message: '请同意用户协议和隐私政策' };
    }

    return { isValid: true };
  }

  /**
   * 保存认证数据
   */
  private async saveAuthData(authToken: AuthToken): Promise<void> {
    const preferences = globalThis.abilityContext.getPreferences('auth_prefs');
    await preferences.put('auth_token', authToken.token);
    await preferences.put('refresh_token', authToken.refreshToken);
    await preferences.put('token_expires_at', authToken.expiresAt);
    await preferences.flush();
  }

  /**
   * 保存用户信息
   */
  private async saveUserInfo(user: User): Promise<void> {
    const preferences = globalThis.abilityContext.getPreferences('user_prefs');
    await preferences.put('current_user', JSON.stringify(user));
    await preferences.flush();
  }

  /**
   * 加载当前用户信息
   */
  private async loadCurrentUser(): Promise<void> {
    try {
      const preferences = globalThis.abilityContext.getPreferences('user_prefs');
      const userJson = await preferences.get('current_user', '');
      
      if (userJson) {
        this.currentUser = JSON.parse(userJson as string);
      }
    } catch (error) {
      console.error('Failed to load user info:', error);
    }
  }

  /**
   * 获取存储的token
   */
  private async getStoredToken(): Promise<string | null> {
    try {
      const preferences = globalThis.abilityContext.getPreferences('auth_prefs');
      const token = await preferences.get('auth_token', '');
      return token as string || null;
    } catch (error) {
      console.error('Failed to get stored token:', error);
      return null;
    }
  }

  /**
   * 获取存储的刷新token
   */
  private async getStoredRefreshToken(): Promise<string | null> {
    try {
      const preferences = globalThis.abilityContext.getPreferences('auth_prefs');
      const refreshToken = await preferences.get('refresh_token', '');
      return refreshToken as string || null;
    } catch (error) {
      console.error('Failed to get stored refresh token:', error);
      return null;
    }
  }

  /**
   * 检查token是否过期
   */
  private isTokenExpired(token: AuthToken): boolean {
    return Date.now() >= token.expiresAt;
  }

  /**
   * 清除认证数据
   */
  private async clearAuthData(): Promise<void> {
    try {
      const authPrefs = globalThis.abilityContext.getPreferences('auth_prefs');
      await authPrefs.delete('auth_token');
      await authPrefs.delete('refresh_token');
      await authPrefs.delete('token_expires_at');
      await authPrefs.flush();

      const userPrefs = globalThis.abilityContext.getPreferences('user_prefs');
      await userPrefs.delete('current_user');
      await userPrefs.flush();
    } catch (error) {
      console.error('Failed to clear auth data:', error);
    }
  }
}